﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Threading;
using System.Drawing;

namespace WebMacros
{
    public class script1
    {
        private Point m_current;
        private string m_key;
        private string m_id;
        private string m_password;

        private Dictionary<string,List<string>> m_works = new Dictionary<string,List<string>>();

        public script1( TextBox logbox, string id, string password )
        {
            m_id = id;
            m_password = password;

            Dictionary<string, Point> subject = new Dictionary<string, Point>();

            // 사회학개론
            subject["사회학개론"] = new Point( 377, 658 );
            m_works["사회학개론"] = new List<string>();

            // 산업심리학
            subject["산업심리학"] = new Point( 377, 685 );
            m_works["산업심리학"] = new List<string>();

            // 심리학개론
            subject["심리학개론"] = new Point( 377, 708 );
            m_works["심리학개론"] = new List<string>();

            // 인간관계론
            subject["인간관계론"] = new Point( 377, 733 );
            m_works["인간관계론"] = new List<string>();

            uint reTryCount = 0;
            do
            {
                logbox.Invoke(new MethodInvoker(delegate()
                    {
                        logbox.AppendText(string.Format("{0} 시도... \r\n", reTryCount));
                    }));
                
                foreach( KeyValuePair<string, Point> pt in subject )
                {
                    m_current = pt.Value;
                    m_key = pt.Key;

                    logbox.Invoke(new MethodInvoker(delegate()
                    {
                        logbox.AppendText(string.Format("이번 과목 '{0}' \r\n", m_key));
                    }));

                    Thread th = new Thread( new ParameterizedThreadStart( ThreadMain ) );
                    th.Start( this );

                    th.Join( new TimeSpan( 2, 0, 0 ) );
                }
                ++reTryCount;
            } while( m_works["사회학개론"].Count > 0
                || m_works["산업심리학"].Count > 0
                || m_works["심리학개론"].Count > 0
                || m_works["인간관계론"].Count > 0 );

            logbox.Invoke(new MethodInvoker(delegate()
                    {
                        logbox.AppendText("완료!!");
                    }));
        }

        public void ThreadMain( object obj )
        {
            script1 pThis = obj as script1;
            using( Scripter tab1 = new Scripter( 1, Scripter.IE, true ) )
            {
                tab1.GotoURL( "http://www.paranhanul.net/" );
                tab1.Size( 1076, 938 );

                tab1.Line( string.Format("TAG POS=1 TYPE=INPUT:TEXT FORM=NAME:LeftLoginForm ATTR=ID:ID CONTENT={0}", m_id ) );
                tab1.Line("SET !ENCRYPTION NO");
                tab1.Line( string.Format("TAG POS=1 TYPE=INPUT:PASSWORD FORM=NAME:LeftLoginForm ATTR=ID:PASSWD CONTENT={0}", m_password ) );
                tab1.Click( 194, 191 );
                tab1.Wait( 3.0f );
                tab1.Click( 595, 57 );
                tab1.Wait( 3.0f );

                tab1.Play();

                tab1.Line( "CODE:TAB T=1" );
                tab1.Wait( 3.0f );
                tab1.Click( pThis.m_current.X, pThis.m_current.Y );

                tab1.Play();

                Tab2();
            }            
        }

        void Tab2()
        {
            Scripter tab2 = new Scripter( 2, Scripter.IE, false );

            tab2.Wait( 5.0f );

            // 메인화면 데이터 가져오기( 전체 수강테이블 )
            tab2.Line( "FRAME NAME=ContentiFrame" );
            tab2.Line( "TAG POS=6 TYPE=TABLE ATTR=TXT:* EXTRACT=TXT" );

            // 왼쪽 트리 데이터 가져오기
            tab2.Line( "FRAME NAME=NODEListiFrame" );
            tab2.Line( "TAG POS=1 TYPE=TABLE ATTR=TXT:* EXTRACT=TXT" );

            tab2.Play();
            
            List<string> works = MainTableParse( tab2.Extract( 1 ) );
            m_works[m_key] = works;

            List<Dictionary<string, int>> sideTable = SideTableParse( tab2.Extract( 2 ) );

            foreach( string work in new List<string>( works ) )
            {
                int selectedID = 0;
                Dictionary<string, int> selected = FindSideTable( out selectedID, work, sideTable );

                tab2.Line( "CODE:TAB T=1" );
                tab2.Wait( 5.0f );

                // Select
                tab2.Line( "FRAME NAME=NODEListiFrame" );
                tab2.Line( string.Format( "TAG POS=1 TYPE=SPAN ATTR=ID:SN_NM{0}", selectedID ) );

                tab2.Wait( 2.0f );

                tab2.Line( "FRAME NAME=LectureEpiiFrame" );
                tab2.Line( "TAG POS=6 TYPE=TABLE ATTR=TXT:* EXTRACT=TXT" );

                tab2.Play();

                string extract = tab2.Extract(1);
                if (extract == "NODATA"
                    || string.IsNullOrEmpty(extract))
                {
                    continue;
                }
                
                Dictionary<string, TimeSpan> lecture = LectureTable(extract);

                // 종료 조건 두번째 체크
                if (lecture.Count == 0)
                {
                    m_works[m_key].Remove(work);
                }

                tab2.Line("CODE:TAB T=1");
                tab2.Wait(1.0f);

                foreach( KeyValuePair<string, TimeSpan> now in lecture )
                {
                    int id = selected[now.Key];

                    tab2.Line( "FRAME NAME=NODEListiFrame" );
                    tab2.Line( string.Format( "TAG POS=1 TYPE=SPAN ATTR=ID:SN_NM{0}", id ) );

                    tab2.Wait( 30.0f );

                    tab2.Wait( ( float )now.Value.TotalSeconds + 15.0f );

                    // 학습종료버튼
                    tab2.Line( "FRAME NAME=main" );
                    tab2.Click( 42, 14 );

                    tab2.Wait( 20.0f );
                }

                tab2.Play( 999999 );
            }
        }

        Dictionary<string, int> FindSideTable( out int selectedID, string findKey, List<Dictionary<string, int>> totalLecture )
        {
            Dictionary<string, int> selected = null;
            selectedID = 0;

            foreach( Dictionary<string, int> lecture in totalLecture )
            {
                if( lecture.ContainsKey( findKey ) )
                {
                    selectedID = lecture[findKey];
                    selected = lecture;
                    break;
                }
            }

            return selected;
        }

        Dictionary<string, TimeSpan> LectureTable( string extract )
        {
            Dictionary<string, TimeSpan> datas = new Dictionary<string, TimeSpan>();
            string[] lines = extract.Split( new string[] { "#NEWLINE#" }, StringSplitOptions.None );
            foreach( string line in lines )
            {
                string[] data = line.Split( new string[] { "#NEXT#" }, StringSplitOptions.None );

                try
                {
                    TimeSpan endTime = TimeSpan.Parse( data[2] );
                    TimeSpan current = TimeSpan.Parse( data[3] );

                    if( endTime > current )
                    {
                        datas[data[0].Trim()] = endTime - current;
                    }
                }
                catch( System.FormatException )
                {
                }
            }

            return datas;
        }

        List<Dictionary<string, int>> SideTableParse( string sideTable )
        {
            List<Dictionary<string, int>> result = new List<Dictionary<string, int>>();
            string[] weeks = sideTable.Split( new string[] { "\r\n\r\n" }, StringSplitOptions.None );
            foreach( string week in weeks )
            {
                Dictionary<string, int> sideTree = new Dictionary<string, int>();
                string[] lines = week.Split( new string[] { "\r\n" }, StringSplitOptions.None );

                foreach( string line in lines )
                {
                    if( line.Length != 0 )
                    {
                        string id = line.Substring( line.Length - 6 );
                        string name = line.Substring( 0, line.Length - 12 );

                        // 그냥 넣으면 안되고, 몇 주차에 무슨 강의인지 알아야됨
                        sideTree[name.Trim()] = Convert.ToInt32( id );
                    }
                }

                result.Add( sideTree );
            }

            return result;
        }

        List<string> MainTableParse( string mainTable )
        {
            List<string> result = new List<string>();

            string[] lines = mainTable.Split( new string[] { "#NEWLINE#" }, StringSplitOptions.None );
            foreach( string line in lines )
            {
                string[] data = line.Split( new string[] { "#NEXT#" }, StringSplitOptions.None );

                // Column
                if( lines[0].Equals( line ) )
                {
                    /*
                    foreach( string txt in data )
                    {
                        view.Columns.Add( txt );
                    }
                     * */
                }
                else // data
                {
                    // view.Items.Add( new ListViewItem( data ) );

                    if( data.Length > 8 )
                    {
                        string temp = data[8].Trim();
                        if( temp != "100.00%"
                            && temp != "-"
                            && data[3] != "학습종료")
                        {
                            result.Add( data[1].Trim() );
                        }
                    }
                }
            }

            return result;
        }
    }
}
